package pl.ppsoft.fixlang;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class WordsManagerActivity extends ListActivity {

	public static final int ADD_WORD_DIALOG = 1;
	public static final int EDIT_WORD_DIALOG = 2;
	public static final int DEL_WORD_DIALOG = 3;
	
	public static final String LESSON_ID_PARAM = "WordLessonId";	
	public static final String LESSON_NAME_PARAM = "WordLessonName";
		
    private DbAdapter db;
	private String sortCol = DbAdapter.WORD_ROWID;
	private boolean sortDesc = false;
    private Cursor wordsCursor;
    private long lessonId, selectedWordId;
    private int selectedPosition;
    
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word_manager);
        
        db = new DbAdapter(this);
        db.open();

        registerForContextMenu( getListView() );        

        Bundle extras = getIntent().getExtras();
        lessonId = extras.getLong(LESSON_ID_PARAM, -1);
                        
        ((TextView)this.findViewById( R.id.title_text )).setText( extras.getString( LESSON_NAME_PARAM ) );
        
        loadWords(sortCol, sortDesc);
        ((TextView)findViewById(R.id.row_counter)).setText( wordsCursor.getCount() + "" );        
    }
	
	@Override
	protected void onDestroy() {
		db.close();

		super.onDestroy();
	}

	private void loadWords( String sort, boolean desc ) {
		if ( wordsCursor != null ) {
			wordsCursor.close();
		}

		wordsCursor = db.fetchManageWords(lessonId, sort, desc);		
        startManagingCursor(wordsCursor);

        String[] from = new String[]{DbAdapter.WORD_QUESTION, DbAdapter.WORD_ANSWER, DbAdapter.WORD_EXAMPLE};
        int[] to = new int[]{R.id.question, R.id.answer, R.id.example};
        
        final int exampleIndex = wordsCursor.getColumnIndex( DbAdapter.WORD_EXAMPLE );
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.word_manager_row, wordsCursor, from, to);
        adapter.setViewBinder( new SimpleCursorAdapter.ViewBinder() {
			
			@Override
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if ( columnIndex == exampleIndex ) {
					String example = cursor.getString(columnIndex);
					if ( example == null || example.length() == 0 ) {
						view.setVisibility( View.GONE );
					} else {
						((TextView)view).setText( example );
						view.setVisibility( View.VISIBLE );
					}
					return true;
				}
				return false;
			}
		});
        setListAdapter(adapter);   
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.words_manager_menu, menu);
                
        return super.onCreateOptionsMenu(menu);
    }
		
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_sort_question:
            	sortList( item,DbAdapter.WORD_QUESTION, false ); 
            	return true;
            case R.id.menu_sort_answer:
            	sortList( item,DbAdapter.WORD_ANSWER, false ); 
            	return true;
            default:
                return super.onOptionsItemSelected(item);                
        }
    }
    
    private void sortList(MenuItem item, String name, boolean desc) {
    	if ( sortCol.equals( name ) ) {
    		sortDesc = !sortDesc;
    	} else {
    		sortDesc = desc;
    	}
    	item.setChecked(true);
    	sortCol = name;
    	loadWords( name, sortDesc );     	
    }

    private void onModify() {
        wordsCursor.requery();
        ((TextView)findViewById(R.id.row_counter)).setText( wordsCursor.getCount() + "" );
    }
    
    @Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ADD_WORD_DIALOG:
            final View wordAddView = LayoutInflater.from(this).inflate(R.layout.word_dialog, null); 
            
            final EditText questionAdd = (EditText)wordAddView.findViewById( R.id.word_question );
            final EditText answerAdd = (EditText)wordAddView.findViewById( R.id.word_answer );
            final EditText exampleAdd = (EditText)wordAddView.findViewById( R.id.word_example );
            
	         return new AlertDialog.Builder(this)
             .setTitle(R.string.word_add_title)
             .setView(wordAddView)
             .setPositiveButton(R.string.btn_add, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int whichButton) {                	                      
                     String qvalue = questionAdd.getText().toString();                     
                     String avalue = answerAdd.getText().toString();
                     String evalue = exampleAdd.getText().toString();
                     if ( qvalue == null || qvalue.length() == 0 || avalue == null || avalue.length() == 0 ) {
                    	 Toast.makeText(WordsManagerActivity.this, R.string.word_invalid, Toast.LENGTH_LONG).show();
                     } else {                     
	                	 db.addWord( lessonId, qvalue, avalue, evalue );
	                	 onModify();
                     }
                 }
             })
             .setNegativeButton(R.string.btn_cancel, null)
             .create();     				
		case EDIT_WORD_DIALOG:
			View wordEditView = LayoutInflater.from(this).inflate(R.layout.word_dialog, null); 

            final EditText questionEdit = (EditText)wordEditView.findViewById( R.id.word_question );
            final EditText answerEdit = (EditText)wordEditView.findViewById( R.id.word_answer );
            final EditText exampleEdit = (EditText)wordEditView.findViewById( R.id.word_example );

			return new AlertDialog.Builder(this)
			.setTitle(R.string.word_edit_title)
			.setView(wordEditView)
			.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener() {
			     public void onClick(DialogInterface dialog, int whichButton) {
                     String qvalue = questionEdit.getText().toString();                     
                     String avalue = answerEdit.getText().toString();
                     String evalue = exampleEdit.getText().toString();
                     if ( qvalue == null || qvalue.length() == 0 || avalue == null || avalue.length() == 0 ) {
                    	 Toast.makeText(WordsManagerActivity.this, R.string.word_invalid, Toast.LENGTH_LONG).show();
                     } else {                     
    			    	 db.updateWord( selectedWordId, lessonId, qvalue, avalue, evalue );
    			    	 onModify();
                     }
			     }
			 })
			.setNegativeButton(R.string.btn_cancel, null)
			.create();     				
		case DEL_WORD_DIALOG:
        	return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(R.string.word_really_delete)
            .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                	db.deleteWord(selectedWordId, lessonId);
                	onModify();
                }

            })
            .setNegativeButton(R.string.btn_no, null)
            .show();
		default:
	    	return super.onCreateDialog(id);
		}
	}

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.word_modify_menu, menu);    		
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo ) item.getMenuInfo();
    	selectedPosition = info.position;
    	selectedWordId = info.id;

    	switch(item.getItemId()) {
	    	case R.id.menu_editword:
	        	this.showDialog(EDIT_WORD_DIALOG);        	
	        	return true;
	        case R.id.menu_delword:
	        	this.showDialog(DEL_WORD_DIALOG);        	
	        	return true;
	        default:
	            return super.onContextItemSelected(item);
        }    	
    }

    public void onAddWord(View v) {
    	this.showDialog(ADD_WORD_DIALOG);    	
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);

        EditText question = (EditText)dialog.findViewById( R.id.word_question );        
        EditText answer = (EditText)dialog.findViewById( R.id.word_answer );
        EditText example = (EditText)dialog.findViewById( R.id.word_example );
        switch (id) {
            case ADD_WORD_DIALOG:
            	question.requestFocus();
            	question.setText("");
            	answer.setText("");
            	example.setText("");
            	break;
            case EDIT_WORD_DIALOG:
            	question.requestFocus();
            	Cursor row = (Cursor)getListView().getItemAtPosition(this.selectedPosition);
            	question.setText(row.getString( row.getColumnIndex( DbAdapter.WORD_QUESTION )));
            	answer.setText(row.getString( row.getColumnIndex( DbAdapter.WORD_ANSWER )));
            	example.setText(row.getString( row.getColumnIndex( DbAdapter.WORD_EXAMPLE )));
            	break;            	
        }
    }
    
}
